<?php

/**
 * @name user.php
 * @copyright (c) 2011
 */
App::uses('AuthComponent', 'Controller/Component');

class User extends AppModel {

    var $name = 'User';

    /**
     * associations
     */
    var $hasAndBelongsToMany = array(
        'Project' => array(
            'className' => 'Project',
            'joinTable' => 'users_projects',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'project_id',
            'unique' => true,
            'conditions' => array('Project.deleted'=>'n'),
            'fields' => '',
            'order' => array('Project.name'=>'ASC'),
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        )
    );

    public $hasMany = array(
        'Ticket' => array(
            'className' => 'Ticket',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'TicketHistory' => array(
            'className' => 'TicketHistory',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );


    var $belongsTo = array(
        'Group' => array(
            'className' => 'Group',
            'foreignKey' => 'group_id',
            'conditions' => '',
            'order' => '',
            'limit' => '',
            'dependent' => false
        ),
        'Branch' => array(
            'className' => 'Branch',
            'foreignKey' => 'branch_id',
            'conditions' => '',
            'order' => '',
            'limit' => '',
            'dependent' => false
        ),
         'Department' => array(
            'className' => 'Department',
            'foreignKey' => 'department_id',
            'conditions' => '',
            'order' => '',
            'limit' => '',
            'dependent' => false
        )
    );



    public function beforeSave($data = null) {
       // if( isset($this->data[$this->alias]['password']) ) {
         //   $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
        //}
        return true;
    }

    function getProjectManagers($project_id = null) {
        $user_ids = array();
        $this->bindModel(array('hasMany' => array('UsersProject')));
        $conditions = array(
            'UsersProject.support_type' =>'Manager',
        );
        if($project_id != null){
            $conditions['UsersProject.project_id'] = $project_id;
        }
        $usr =  $this->UsersProject->find('all', array('conditions' => $conditions, 'recursive' => -1));
        foreach($usr as $u){
            $user_ids[]=$u['UsersProject']['user_id'];
        }
        $conditions = array('User.deleted' => 'n','User.active' => 'y');
        if(!empty($user_ids)){
            $conditions['User.id'] = $user_ids;
        }
        else{
            return array();
        }
        # fetch the data and return it.
        $contain = array(
            'Branch'=>array('fields' => array('Branch.id', 'Branch.name'))
        );
        return $this->find('all', array('contain'=>$contain,'conditions' => $conditions ,'recursive' => 1));
    }


    function getProjectUsers($project_id = null) {
        $user_ids = array();
        $this->bindModel(array('hasMany' => array('UsersProject')));
        $conditions = array(
            'UsersProject.project_id' =>$project_id,
        );
        $usr =  $this->UsersProject->find('all', array('conditions' => $conditions, 'recursive' => -1));
        foreach($usr as $u){
            $user_ids[]=$u['UsersProject']['user_id'];
        }
        $conditions = array('User.deleted' => 'n','User.active' => 'y');
        if(!empty($user_ids)){
            $conditions['User.id'] = $user_ids;
        }
        else{
            return array();
        }
        # fetch the data and return it.
        $contain = array(
            'Branch'=>array('fields' => array('Branch.id', 'Branch.name'))
        );
        return $this->find('all', array('contain'=>$contain,'conditions' => $conditions ,'recursive' => 1));
    }


    function getWithMoreData($param = null,$user_id=null) {
        $user_ids = array();
        if($param != null){
            $this->bindModel(array('hasMany' => array('UsersProject')));
            $conditions = array(
                'UsersProject.support_type' =>$param,
            );
            $usr =  $this->UsersProject->find('all', array('conditions' => $conditions, 'recursive' => -1));
            foreach($usr as $u){
                $user_ids[]=$u['UsersProject']['user_id'];
            }
            if($user_id != null){
                $user_ids[] = $user_id;
            }
        }

        $conditions = array('User.deleted' => 'n','User.active' => 'y');
        if(!empty($user_ids)){
            $conditions['User.id'] = $user_ids;
        }
        # fetch the data and return it.
        $contain = array(
            'Branch'=>array('fields' => array('Branch.id', 'Branch.name'))
        );
        return $this->find('all', array('contain'=>$contain,'conditions' => $conditions ,'recursive' => 1));
    }

    /**
     * This function retrieves all the users from the database tables users.
     * @name getAllUsers
     * @param void
     * @return mixed. Array containing the data retrieved.
     * @access public
     */
    function getAllUsers() {
        # fetch the data and return it.
        return $this->find('all', array('conditions' => array('User.deleted' => 'n'), 'recursive' => -1));
    }

    /**
     * This function retrieves the user data based upon his/her id
     * @name getUserById
     * @param string $userId string holding the user id.his parameter is defaulted to null.
     * When it is null it means that cake is going to use the ActiveRecord system to retrieve the data.
     * @return mixed. Array containing the user data.
     * @access public
     */
    function getUserById($userId = null) {
        $conditions = array(
            'User.id' => $userId,
            'User.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => 1));
    }

    # User Data manipulation functions
    /**
     * This function retrieves the user by his login name
     * @name getUserByLoginName
     * @param string $loginName
     * @return array of data containing the login name and the user password
     * @access public
     */

    function getUserByLoginName($loginName = null) {
        # search condition
        $conditions = array(
            'User.username' => $loginName,
            'User.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => 1));
    }


    function validateUsername($username = null)
    {
        $data = $this->getUserByLoginName($username);
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    function getUserProjectById($id = null){
        $conditions = array(
            'User.id' => $id,
            'User.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return  $this->find('first', array('contain'=>array('Project'),'conditions' => $conditions, 'recursive' => 1));
    }

    function checkUsersProject($user_id = null, $project_id=null,$support_type=null){
        $this->bindModel(array('hasMany' => array('UsersProject')));
        if($support_type == 'Manager'){
            $conditions = array(
                'UsersProject.project_id' => $project_id,
                'UsersProject.support_type' => $support_type
            );
            //Do we have a manager for this project already
            $re = $this->UsersProject->find('first', array('conditions' => $conditions, 'recursive' => -1));
            if($re){
                return array('status'=>true,'msg'=>'A manager already exist for this project');
            }
            else{
                return  array('status'=>false);
            }
        }
        $conditions = array(
            'UsersProject.user_id' => $user_id,
            'UsersProject.project_id' => $project_id
        );
        $re = $this->UsersProject->find('first', array('conditions' => $conditions, 'recursive' => -1));
        if($re){
            return array('status'=>true,'msg'=>'User has been assigned to the project already');
        }
        else{
            return  array('status'=>false);
        }
    }


    function deleteUsersProject($ids = null){
        $this->bindModel(array('hasMany' => array('UsersProject')));
        $re = $this->UsersProject->deleteAll(array('UsersProject.id' => $ids), false);
        if($re){
            return true;
        }
        else{
            return  false;
        }
    }
}